<template>
  <div class="m-y-10 flex">
    <el-avatar :src="curUser.avatar" :size="30" />
    <div class="flex-1 align-items-end m-l-10">
      <div class="flex">
        <el-input
          :id="textareaId"
          type="textarea"
          :placeholder="placeholder"
          v-model="content"
          :autosize="{ minRows: 2 }"
          class="flex-1"
          :disabled="loading"
        />
        <el-button
          size="small"
          type="primary"
          class="m-l-10"
          @click="submitReply"
          :loading="loading">
          发布
        </el-button>
      </div>
      <div class="m-t-10">
        <el-popover placement="bottom" width="400" trigger="click">
          <emoji @emoji="handleEmoji" />
          <el-button slot="reference" size="mini" round>
            <svg-icon icon-name="emoji"/>&nbsp;表情
          </el-button>
        </el-popover>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { formatComment } from '../format';

export default {
  name: 'reply-container',
  props: {
    curCommentId: Number,
    receiveCommentId: Number,
    receiveUserId: Number,
    receiveUserNickname: String,
  },
  data() {
    return {
      content: '',
      loading: false,
      textareaId: new Date().getTime(),
    };
  },
  computed: {
    ...mapState({
      curUser: 'currentUser',
    }),
    isReplyingOthers() {
      return this.curCommentId !== this.receiveCommentId;
    },
    placeholder() {
      return this.isReplyingOthers ? `回复 ${this.receiveUserNickname}：` : '写下你的评论...';
    },
    submitReplyParams() {
      return {
        placement: 'ProductFile',
        placementId: this.$route.params.docId,
        mainFloorId: this.curCommentId, // 当前主楼（回答）的id
        receiveCommentId: this.receiveCommentId, // 回复的是哪个评论
        receiveUserId: this.receiveUserId, // 被回复人的id
        replySubFloor: this.isReplyingOthers, // 是不是回复楼中落
        content: this.content.trim(),
      };
    },
  },
  methods: {
    // 写评论
    submitReply() {
      if (!this.content.trim()) return;
      this.loading = true;
      this.$api.comments.create(this.submitReplyParams)
        .then((res) => {
          this.content = '';
          this.$emit('replied', formatComment(res.data));
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    handleEmoji(item) {
      // el-input 套了一层，使用ref不能获取到 textarea
      const inputArea = document.getElementById(this.textareaId);
      function changeSelectedText(obj, str) {
        if (window.getSelection) {
          inputArea.setRangeText(str);
          inputArea.selectionStart += str.length;
          inputArea.focus();
        } else if (document.selection) {
          obj.focus();
          const sel = document.selection.createRange();
          sel.text = str;
        }
      }
      changeSelectedText(inputArea, item);
      this.content = inputArea.value;
    },
    clearContent() {
      this.content = '';
    },
  },
  watch: {
    receiveCommentId() { this.clearContent(); },
  },
};
</script>

<style></style>
